package com.jwthhealth_pub.community.view;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.jwthhealth_pub.R;
import com.jwthhealth_pub.common.base.BaseActivity;
import com.jwthhealth_pub.common.view.TitleLayout;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.jwthhealth_pub.common.LogUtil.makeLogTag;

/**
 * 上传身份证
 * Created by liuzhen on 2017/12/18.
 */

public class CommunityDocApplyIdCardActivity extends BaseActivity {

    private static final String TAG = makeLogTag(CommunityDocApplyIdCardActivity.class);

    private static final int PERMISSION_CAMERA = 0;
    private static final int PERMISSION_WRITE_EXTERNAL_STORAGE = 1;

    public static final int TAKE_PHOTO = 2;
    public static final int CHOOSE_PHOTO = 3;

    @BindView(R.id.title_layout)
    TitleLayout titleLayout;
    @BindView(R.id.iv_community_docapply_idcard_front)
    ImageView ivIdCardFront;
    @BindView(R.id.iv_community_docapply_idcard_reverse)
    ImageView ivIdCardReverse;

    private Uri imageUri;
    private int mTarget;

    @Override
    protected void title() {
        titleLayout.setOnTitleLayoutListener(new TitleLayout.TitleLayoutListener() {
            @Override
            public void leftclick() {
                finish();
            }

            @Override
            public void leftTextClick() {

            }

            @Override
            public void rightclick() {

            }

            @Override
            public void rightTextClick() {

            }
        });
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_community_docapply_idcard);
        ButterKnife.bind(this);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{android.Manifest.permission.CAMERA}, PERMISSION_CAMERA);
        }


        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_SETTINGS}, PERMISSION_WRITE_EXTERNAL_STORAGE);
        }

    }

    @OnClick({R.id.btn_community_docapply_idcard_front, R.id.btn_community_docapply_idcard_reverse})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_community_docapply_idcard_front:
                showPicDialog(0);
                break;
            case R.id.btn_community_docapply_idcard_reverse:
                showPicDialog(1);
                break;
        }
    }

    private void showPicDialog(final int i) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = View.inflate(this, R.layout.item_community_idcard_piclist, null);
        builder.setView(dialogView);

        View camera = dialogView.findViewById(R.id.tv_idcard_camera);
        View album = dialogView.findViewById(R.id.tv_idcard_album);

        final AlertDialog alertDialog = builder.create();

        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                takePhoto(i);
                alertDialog.dismiss();
            }
        });

        album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openAlbum(i);
                alertDialog.dismiss();
            }
        });


        alertDialog.show();
    }

    private void openAlbum(int i) {
        this.mTarget = i;

        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO);
    }

    private void takePhoto(int page) {
        this.mTarget = page;

        //创建file对象，用于存储拍照后的图片；
        File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
        Log.d(TAG, outputImage.getPath());
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();

        } catch (Exception e) {
            Log.d(TAG, e.toString());
        }

        if (Build.VERSION.SDK_INT >= 24) {
//            imageUri = FileProvider.getUriForFile(this,"com.gyq.cameraalbumtest.fileprovider", outputImage);
            imageUri = FileProvider.getUriForFile(this,"com.jwthhealth.fileprovider", outputImage);
        } else {
            imageUri = Uri.fromFile(outputImage);
        }

        //启动相机程序
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, TAKE_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    try {
                        Bitmap bm = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        if (mTarget == 0)
                            ivIdCardFront.setImageBitmap(bm);
                        else
                            ivIdCardReverse.setImageBitmap(bm);
                        File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
                        outputImage.delete();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
                break;
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    if (Build.VERSION.SDK_INT >= 19) {  //4.4及以上的系统使用这个方法处理图片；
                        handleImageOnKitKat(data);
                    } else {
                        handleImageBeforeKitKat(data);  //4.4及以下的系统使用这个方法处理图片
                    }
                }
            default:
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_CAMERA:
                if (grantResults.length < 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    Log.d(TAG, "camera permisson refuse");
                }
                break;
            case PERMISSION_WRITE_EXTERNAL_STORAGE:
                if (grantResults.length < 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    Log.d(TAG, "write_external permisson refuse");
                }
                break;
            default:
                break;
        }
    }


    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    /**
     * 4.4及以上的系统使用这个方法处理图片
     *
     * @param data
     */
    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            //如果document类型的Uri,则通过document来处理
            String docID = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docID.split(":")[1];     //解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;

                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/piblic_downloads"), Long.valueOf(docID));

                imagePath = getImagePath(contentUri, null);

            }

        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            //如果是content类型的uri，则使用普通方式使用
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            //如果是file类型的uri，直接获取路径即可
            imagePath = uri.getPath();

        }

        displayImage(imagePath);
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        //通过Uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }


    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bm = BitmapFactory.decodeFile(imagePath);
            if (mTarget == 0)
                ivIdCardFront.setImageBitmap(bm);
            else
                ivIdCardReverse.setImageBitmap(bm);
        } else {
            Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
        }
    }
}
